package com.gk.panda.apis.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.gk.panda.commons.result.Result;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/kaptcha")
@Api(tags = "验证码")
public class KaptchaController {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value = "获取验证码")
    @RequestMapping()
    public Result<Map<String, String>> getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();

        response.setDateHeader("Expires", 0);

        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");

        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");

        // return a jpeg
        response.setContentType("image/jpeg");

        // create the text for the image
        String capText = captchaProducer.createText();

        // store the text in the session
//        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        String uuid = IdUtil.simpleUUID();
        redisTemplate.opsForValue().set("KAPTCHA_KEY"+uuid,capText,600, TimeUnit.SECONDS);

        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();

        // write the data out
        ImageIO.write(bi, "jpg", os);
        try {
            os.flush();
        } finally {
            os.close();
        }
        Map<String, String> resultMap = new HashMap();
        resultMap.put("uuid", uuid);
        resultMap.put("img", "data:image/jpg;base64,"+Base64.encode(os.toByteArray()));
        return Result.ok(resultMap);
    }

}
